package homework3;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CountKeyword {
    public static void main(String[] args) {
        String filePath = "article.txt";
        String keyword = "黑马";

        int count = countKeyword(filePath, keyword);
        System.out.println("关键字: " + keyword + " 出现的次数为：" + count);
    }

    public static int countKeyword(String filePath, String keyword) {
        int count = 0;
        //读完之后,自动关毕,关闭机制
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            StringBuilder content = new StringBuilder();
            String line;

            // 读取文章内容并存储为字符串
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }

            // 使用字符串的indexOf()方法统计关键字出现的次数
            int index = content.indexOf(keyword);
            while (index != -1) {
                count++;
                index = content.indexOf(keyword, index + keyword.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
            // 在文件末尾换行追加写入关键字出现的次数
            writer.newLine();
            writer.write(String.valueOf(count));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return count;
    }
}